<?php
use app\api\controller\model\WechatModel;
use app\api\controller\model\XcxPageModel;
use EasyWeChat\Factory;
// 公共助手函数

if (!function_exists('__')) {

    /**
     * 获取语言变量值
     * @param string $name 语言变量名
     * @param array $vars 动态变量值
     * @param string $lang 语言
     * @return mixed
     */
    function __($name, $vars = [], $lang = '')
    {
        if (is_numeric($name) || !$name)
            return $name;
        if (!is_array($vars)) {
            $vars = func_get_args();
            array_shift($vars);
            $lang = '';
        }
        return \think\Lang::get($name, $vars, $lang);
    }

}

if (!function_exists('format_bytes')) {

    /**
     * 将字节转换为可读文本
     * @param int $size 大小
     * @param string $delimiter 分隔符
     * @return string
     */
    function format_bytes($size, $delimiter = '')
    {
        $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
        for ($i = 0; $size >= 1024 && $i < 6; $i++)
            $size /= 1024;
        return round($size, 2) . $delimiter . $units[$i];
    }

}

if (!function_exists('datetime')) {

    /**
     * 将时间戳转换为日期时间
     * @param int $time 时间戳
     * @param string $format 日期时间格式
     * @return string
     */
    function datetime($time, $format = 'Y-m-d H:i:s')
    {
        $time = is_numeric($time) ? $time : strtotime($time);
        return date($format, $time);
    }

}

if (!function_exists('human_date')) {

    /**
     * 获取语义化时间
     * @param int $time 时间
     * @param int $local 本地时间
     * @return string
     */
    function human_date($time, $local = null)
    {
        return \fast\Date::human($time, $local);
    }

}

if (!function_exists('cdnurl')) {

    /**
     * 获取上传资源的CDN的地址
     * @param string $url 资源相对地址
     * @param boolean $domain 是否显示域名 或者直接传入域名
     * @return string
     */
    function cdnurl($url, $domain = false)
    {
        $url = preg_match("/^https?:\/\/(.*)/i", $url) ? $url : \think\Config::get('upload.cdnurl') . $url;
        if ($domain && !preg_match("/^(http:\/\/|https:\/\/)/i", $url)) {
            if (is_bool($domain)) {
                $public = \think\Config::get('view_replace_str.__PUBLIC__');
                $url = rtrim($public, '/') . $url;
                if (!preg_match("/^(http:\/\/|https:\/\/)/i", $url)) {
                    $url = request()->domain() . $url;
                }
            } else {
                $url = $domain . $url;
            }
        }
        return $url;
    }

}


if (!function_exists('is_really_writable')) {

    /**
     * 判断文件或文件夹是否可写
     * @param    string $file 文件或目录
     * @return    bool
     */
    function is_really_writable($file)
    {
        if (DIRECTORY_SEPARATOR === '/') {
            return is_writable($file);
        }
        if (is_dir($file)) {
            $file = rtrim($file, '/') . '/' . md5(mt_rand());
            if (($fp = @fopen($file, 'ab')) === FALSE) {
                return FALSE;
            }
            fclose($fp);
            @chmod($file, 0777);
            @unlink($file);
            return TRUE;
        } elseif (!is_file($file) OR ($fp = @fopen($file, 'ab')) === FALSE) {
            return FALSE;
        }
        fclose($fp);
        return TRUE;
    }

}

if (!function_exists('rmdirs')) {

    /**
     * 删除文件夹
     * @param string $dirname 目录
     * @param bool $withself 是否删除自身
     * @return boolean
     */
    function rmdirs($dirname, $withself = true)
    {
        if (!is_dir($dirname))
            return false;
        $files = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($dirname, RecursiveDirectoryIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST
        );

        foreach ($files as $fileinfo) {
            $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
            $todo($fileinfo->getRealPath());
        }
        if ($withself) {
            @rmdir($dirname);
        }
        return true;
    }

}

if (!function_exists('copydirs')) {

    /**
     * 复制文件夹
     * @param string $source 源文件夹
     * @param string $dest 目标文件夹
     */
    function copydirs($source, $dest)
    {
        if (!is_dir($dest)) {
            mkdir($dest, 0755, true);
        }
        foreach (
            $iterator = new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS), RecursiveIteratorIterator::SELF_FIRST) as $item
        ) {
            if ($item->isDir()) {
                $sontDir = $dest . DS . $iterator->getSubPathName();
                if (!is_dir($sontDir)) {
                    mkdir($sontDir, 0755, true);
                }
            } else {
                copy($item, $dest . DS . $iterator->getSubPathName());
            }
        }
    }

}

if (!function_exists('mb_ucfirst')) {

    function mb_ucfirst($string)
    {
        return mb_strtoupper(mb_substr($string, 0, 1)) . mb_strtolower(mb_substr($string, 1));
    }

}

if (!function_exists('addtion')) {

    /**
     * 附加关联字段数据
     * @param array $items 数据列表
     * @param mixed $fields 渲染的来源字段
     * @return array
     */
    function addtion($items, $fields)
    {
        if (!$items || !$fields)
            return $items;
        $fieldsArr = [];
        if (!is_array($fields)) {
            $arr = explode(',', $fields);
            foreach ($arr as $k => $v) {
                $fieldsArr[$v] = ['field' => $v];
            }
        } else {
            foreach ($fields as $k => $v) {
                if (is_array($v)) {
                    $v['field'] = isset($v['field']) ? $v['field'] : $k;
                } else {
                    $v = ['field' => $v];
                }
                $fieldsArr[$v['field']] = $v;
            }
        }
        foreach ($fieldsArr as $k => &$v) {
            $v = is_array($v) ? $v : ['field' => $v];
            $v['display'] = isset($v['display']) ? $v['display'] : str_replace(['_ids', '_id'], ['_names', '_name'], $v['field']);
            $v['primary'] = isset($v['primary']) ? $v['primary'] : '';
            $v['column'] = isset($v['column']) ? $v['column'] : 'name';
            $v['model'] = isset($v['model']) ? $v['model'] : '';
            $v['table'] = isset($v['table']) ? $v['table'] : '';
            $v['name'] = isset($v['name']) ? $v['name'] : str_replace(['_ids', '_id'], '', $v['field']);
        }
        unset($v);
        $ids = [];
        $fields = array_keys($fieldsArr);
        foreach ($items as $k => $v) {
            foreach ($fields as $m => $n) {
                if (isset($v[$n])) {
                    $ids[$n] = array_merge(isset($ids[$n]) && is_array($ids[$n]) ? $ids[$n] : [], explode(',', $v[$n]));
                }
            }
        }
        $result = [];
        foreach ($fieldsArr as $k => $v) {
            if ($v['model']) {
                $model = new $v['model'];
            } else {
                $model = $v['name'] ? \think\Db::name($v['name']) : \think\Db::table($v['table']);
            }
            $primary = $v['primary'] ? $v['primary'] : $model->getPk();
            $result[$v['field']] = $model->where($primary, 'in', $ids[$v['field']])->column("{$primary},{$v['column']}");
        }

        foreach ($items as $k => &$v) {
            foreach ($fields as $m => $n) {
                if (isset($v[$n])) {
                    $curr = array_flip(explode(',', $v[$n]));

                    $v[$fieldsArr[$n]['display']] = implode(',', array_intersect_key($result[$n], $curr));
                }
            }
        }
        return $items;
    }

}

if (!function_exists('var_export_short')) {

    /**
     * 返回打印数组结构
     * @param string $var 数组
     * @param string $indent 缩进字符
     * @return string
     */
    function var_export_short($var, $indent = "")
    {
        switch (gettype($var)) {
            case "string":
                return '"' . addcslashes($var, "\\\$\"\r\n\t\v\f") . '"';
            case "array":
                $indexed = array_keys($var) === range(0, count($var) - 1);
                $r = [];
                foreach ($var as $key => $value) {
                    $r[] = "$indent    "
                        . ($indexed ? "" : var_export_short($key) . " => ")
                        . var_export_short($value, "$indent    ");
                }
                return "[\n" . implode(",\n", $r) . "\n" . $indent . "]";
            case "boolean":
                return $var ? "TRUE" : "FALSE";
            default:
                return var_export($var, TRUE);
        }
    }

}

/**
 * 发送变量短信
 *
 * @param string $msg 短信内容
 * @param string $params 最多不能超过1000个参数组
 */
//数据拼接

function sendVariableSMS($msg, $params)
{
    $config = db("gzns_setting")->field("sms_account,sms_password,sms_send_url")->find();
    //创蓝接口参数
    $postArr = array(
        'account' => $config["sms_account"],
        'password' => $config["sms_password"],
        'msg' => $msg,
        'params' => $params,
        'report' => 'true'
    );

    return curlPost($config["sms_send_url"],$postArr);
}

//检验短信验证码
function checkCode($user_name, $code, $that)
{
    //判断是否存在
    $verify = db("gzns_user_verify_code")
        ->where("user_name", $user_name)
        ->where("code", $code)
        ->find();
    if (!$verify) $that->return_msg(400, '错误的验证码!');
    //判断是否过期
    if (time() - $verify["refresh_time"] > 300) $that->return_msg(400, '验证码过期!');//5分钟内 5*60
    $verify["code"] = "";
    db("gzns_user_verify_code")->update($verify);
}
function checkPhone($phone,$id,$that){
    $exist_phone = db("youmi_teacher")->where("id","<>",$id)->where("phone",$phone)->find();
    if($exist_phone) $that->return_msg(400, '改号码已被注册，请联系管理人员!');
}

/**
 * 通过CURL发送HTTP请求
 * @param string $url //请求URL
 * @param array $postFields //请求参数
 * @return mixed
 *
 */
function curlPost($url,$postFields)
{
    $postFields = json_encode($postFields);

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type:application/json;charset=utf-8'   //json版本需要填写  Content-Type: application/json;
        )
    );
    curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
    curl_setopt($ch, CURLOPT_TIMEOUT, 60);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    $ret = curl_exec($ch);
    if (!curl_errno($ch)) {
        $v = curl_getinfo($ch);
    }
    if (false == $ret) {
        $result = curl_error($ch);
    } else {
        $rsp = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if (200 != $rsp) {
            $result = "请求状态 " . $rsp . " " . curl_error($ch);
        } else {
            $result = $ret;
        }
    }
    curl_close($ch);
    return $result;
}

//数据拼接
function getChildren(&$arr1 = [], $arr2 = [], $arr1_field, $arr2_field, $key = 'children')
{
    for ($i = 0; $i < count($arr1); $i++) {
        $arr1[$i][$key] = [];
        for ($j = 0; $j < count($arr2); $j++) {
            if ($arr1[$i][$arr1_field] == $arr2[$j][$arr2_field]) {
                array_push($arr1[$i][$key], $arr2[$j]);
            }
        }
    }
    unset($arr2);
    unset($field);
    unset($key);
}

//创建编号
function createNo()
{
    $book_no = null;
    // 保证不会有重复订单号存在
    while(true){
        $book_no = date('YmdHis').rand(1000,9999); // 订单编号18位
        $book_no_count = db('youmi_course_book')->where("no",$book_no)->count();
        if($book_no_count == 0)
            break;
    }
    return $book_no;
}
//如果是vip订单，增加vip逻辑
function handleProxyOrder($order){
    $order["order_status"] = 1;
    $order["complete_time"] = date('Y-m-d H:i:s');

    $proxy_list = db('gzns_order')
        ->where('serial_number', $order['order_number'])
        ->select();
    foreach ($proxy_list as $k=>$v) {
        handleCourseOrder($v);
    }
    $order["pay_time"] = date('Y-m-d H:i:s');
    db("gzns_order")->update($order);
}
//如果是vip订单，增加vip逻辑
function handleCourseOrder($order){
    $order["order_status"] = 1;
    if ($order["order_type"] == 0) {//0-线上课程
        $order["complete_time"] = date('Y-m-d H:i:s');
    }
//    //发送课程模板消息
//    $third_account = db("gzns_user_third_account")->where("user_id", $order["user_id"])->where("third_type", 1)->find();
//    $user = db("gzns_user_info")->where("id", $order["user_id"])->find();
//    if ($third_account) {
//        $itme = db("gzns_order_item")->where("order_id", $order["id"])->find();
//        $course = db("gzns_course")->where("id", $itme["item_id"])->find();
//        $wechatModel = new WechatModel(1, false);
//        $aptitude_data = [
//            $order["order_number"], //订单号
//            $user["nick_name"], //客户名称
//            $order["actual_price"], //支付金额
//            '' . $course["name"] . ",已支付成功。", //温馨提示
//        ];
//        if ($order["order_type"] == 0) {
//            $page_url = XcxPageModel::$ONLINE_COURSE_DETAIL . "?id=" . $course["id"];
//        } else {
//            $page_url = XcxPageModel::$OFFLINE_COURSE_DETAIL . "?order_id=" . $order["id"];
//        }
//        $wechatModel->successPay($order["user_id"], $third_account["third_open_id"], $aptitude_data, $page_url);
//    }
    $order["pay_time"] = date('Y-m-d H:i:s');
    db("gzns_order")->update($order);
}
//如果是vip订单，增加vip逻辑
function handleVipOrder($order){
    $order["order_status"] = 1;
    $order["complete_time"] = date('Y-m-d H:i:s');
    $apply = db("gzns_order_item oi")
        ->field("uva.*")
        ->join("gzns_user_vip_apply uva","uva.id = oi.item_id","LEFT")
        ->where("order_id",$order["id"])
        ->find();
    $vip = db('gzns_vip_level')->where('id', $apply["vip_level_id"])->find();
    $user_vip = [
        "user_id" => $order["user_id"],
        "vip_level_id" => $apply["vip_level_id"],
        "start_time" => date('Y-m-d H:i:s',time()),
        "end_time" => $apply['end_time'],
        "company_name" => $apply['company_name'],
        "company_credit_code" => $apply['company_credit_code'],
        "company_principal" => $apply['company_principal'],
        "month_notice" => 0,
        "week_notice" => 0,
        "day_notice" => 0,
    ];
    if($apply["vip_type"] == 1){
        $vip_type = "个人会员";
    }else{
        $vip_type = "单位会员";
    }
    $user_vip_level = db("gzns_user_vip_level")->where('user_id', $order["user_id"])->find();
    $user_vip_level_id = null;
    if ($user_vip_level) {
        $user_vip_level_id = $user_vip_level['id'];
        db("gzns_user_vip_level")->where('id',$user_vip_level_id)->update($user_vip);
    } else {
        $user_vip_level_id = db("gzns_user_vip_level")->insertGetId($user_vip);

    }
    if ($apply['vip_type'] == 1) {
        //个人会员，清除员工
        $staff_user_ids = db('gzns_user_vip_stall')->where('master_id', $order['user_id'])->column('user_id');
        db('gzns_user_info')->whereIn('id', $staff_user_ids)->update([
            'user_vip_level_id'=>null
        ]);
        db('gzns_user_vip_stall')->where('master_id', $order['user_id'])->delete();
        //如果当前所在企业为空更新
        $user = db('gzns_user_info')->where('id', $order['user_id'])->find();
        if (!$user['user_vip_level_id']) {
            db('gzns_user_info')->where('id', $order['user_id'])->update([
                'user_vip_level_id' => $user_vip_level_id
            ]);
        }
    } else if ($apply['vip_type'] == 2) {
        //企业会员更新
        db('gzns_user_info')->where('id', $order['user_id'])->update([
            'user_vip_level_id' => $user_vip_level_id
        ]);
        db('gzns_user_vip_stall')->where('user_id', $order['user_id'])->delete();
    }

    db("gzns_user_vip_apply")->where('id',$apply['id'])->update([
        'status' => 3
    ]);

    //发送模板消息
    $third_account = db("gzns_user_third_account")->where("user_id",$order["user_id"])->where("third_type",1)->find();
    $user = db("gzns_user_info")->where("id",$order["user_id"])->find();
    if($third_account){
        $wechatModel = new WechatModel(1, false);
        $aptitude_data =[
            $order["order_number"], //订单号
            $user["nick_name"], //客户名称
            $order["actual_price"], //支付金额
            '您购买了'.$vip_type.':'.$vip["name"].",有效期限:".$user_vip["start_time"]."-".$user_vip["end_time"], //温馨提示
        ];
        $wechatModel->successPay($order["user_id"],$third_account["third_open_id"],$aptitude_data, XcxPageModel::$VIP_DETAIL);
    }
    $order["pay_time"] = date('Y-m-d H:i:s');
    db("gzns_order")->update($order);

}
//创建订单编号
function createOrderNumber()
{
    $order_number = null;
    // 保证不会有重复订单号存在
    while (true) {
        $order_number = date('YmdHis') . rand(1000, 9999); // 订单编号18位
        $orderSnCount = db('gzns_order')->where("order_number", $order_number)->count();
        if ($orderSnCount == 0)
            break;
    }
    return $order_number;
}

function getWchatQrcode($order_number){

    //不带LOGO
    Vendor('phpqrcode.phpqrcode');
    //生成二维码图片
    $object = new \QRcode();
    $level=3;
    $size=4;
    $time = time().''. rand(1000, 9999);
    $_upload_path = ROOT_PATH . 'public/uploads' . DS . "qrcode" . DS.$time.".jpg";
    $_file_path = '/'.'uploads/'. "qrcode" .'/'.$time.".jpg";
    $errorCorrectionLevel =intval($level) ;//容错级别
    $matrixPointSize = intval($size);//生成图片大小
    $object->png($order_number,  $_upload_path, $errorCorrectionLevel, $matrixPointSize, 2);

    return $_file_path;
}
function sendNoticeOrder($order){
    //发送课程模板消息
    $third_account = db("gzns_user_third_account")->where("user_id",$order["user_id"])->where("third_type",1)->find();
    $user = db("gzns_user_info")->where("id",$order["user_id"])->find();
    if($third_account){
        $itme = db("gzns_order_item")->where("order_id",$order["id"])->find();
        $course = db("gzns_course")->where("id",$itme["item_id"])->find();
        $wechatModel = new WechatModel(1, false);
        $aptitude_data =[
            $order["order_number"], //订单号
            $user["nick_name"], //客户名称
            $order["actual_price"], //支付金额
            ''.$course["name"].",已支付成功。", //温馨提示
        ];
        if($order["order_type"] == 0){
            $page_url =  XcxPageModel::$ONLINE_COURSE_DETAIL."?id=".$course["id"];
        }else{
            $page_url =  XcxPageModel::$OFFLINE_COURSE_DETAIL."?order_id=".$order["id"];
        }
        $wechatModel->successPay($order["user_id"],$third_account["third_open_id"],$aptitude_data, $page_url);
    }
}
/**
 * 通过CURL发送HTTP请求
 * @param string $url //请求URL
 * @param array $postFields //请求参数
 * @return mixed
 *
 */
function curlRequest($url='',$postFields=[],$method="GET",$header=[])
{


    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$url);
//    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
//            'Content-Type:application/json;charset=utf-8'   //json版本需要填写  Content-Type: application/json;
//        )
//    );
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    if (strtoupper($method) == 'POST') {
        $postFields = json_encode($postFields);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
    }
    curl_setopt($ch, CURLOPT_TIMEOUT, 60);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    $ret = curl_exec($ch);
    if (!curl_errno($ch)) {
        $v = curl_getinfo($ch);
    }
    $result = [
//        'success' => true,
//        'data' => null,
//        'msg' => '',
    ];
    if (false == $ret) {
//        $result = curl_error($ch);
        $result = [
            'success' => false,
            'data' => null,
            'msg' => curl_error($ch),
        ];
    } else {
        $rsp = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if (200 != $rsp) {
//            $result = "请求状态 " . $rsp . " " . curl_error($ch);
            $result = [
                'success' => false,
                'data' => null,
                'msg' => "请求状态 " . $rsp . " " . curl_error($ch),
            ];
        } else {
//            $result = $ret;
            $result = [
                'success' => true,
                'data' => $ret,
                'msg' => "",
            ];
        }
    }
    curl_close($ch);
    return $result;
}
function is_index_array(&$arr){
    $keys =  array_keys($arr);
    return array_sum($keys) == array_sum(array_keys($keys))? true : false;
}
